package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.LoginUser;
import com.example.demo.Service.WebSocketService;
import com.example.demo.commom.Result;
import com.example.demo.entity.*;
import com.example.demo.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import com.example.demo.utils.TokenUtils;


import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserMapper userMapper;
    @Resource
    BookWithUserMapper bookWithUserMapper;
    @Resource
    BookMapper bookMapper;
    @Resource
    LendRecordMapper lendRecordMapper;
    @Resource
    ReservationMapper reservationMapper;
    @Autowired
    private WebSocketService webSocketService;

    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res != null) {
            return Result.error("-1", "用户名已重复");
        }
        userMapper.insert(user);
        return Result.success();
    }

    @CrossOrigin
    @PostMapping("/login")
    public Result<?> login(@RequestBody User user) {
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword()));
        if (res == null) {
            return Result.error("-1", "用户名或密码错误");
        }
        String token = TokenUtils.genToken(res);
        res.setToken(token);
        LoginUser loginuser = new LoginUser();
        loginuser.addVisitCount();
        log.info("用户" + res.getUsername() + "登录了");
        log.info("用户信息" + res);
        return Result.success(res);
    }

    @PostMapping
    public Result<?> save(@RequestBody User user) {
        if (user.getPassword() == null) {
            user.setPassword("abc123456");
        }
        userMapper.insert(user);
        return Result.success();
    }

    @PutMapping("/password")
    public Result<?> update(@RequestParam Integer id,
                            @RequestParam String password2) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        User user = new User();
        user.setPassword(password2);
        userMapper.update(user, updateWrapper);
        return Result.success();
    }

    @PutMapping
    public Result<?> password(@RequestBody User user) {
        userMapper.updateById(user);
        return Result.success();
    }

    @PostMapping("/deleteBatch")
    public Result<?> deleteBatch(@RequestBody List<Integer> ids) {
        userMapper.deleteBatchIds(ids);
        return Result.success();
    }

    //cy改
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        // 1. 检查用户是否存在
        User user = userMapper.selectById(id);
        if (user == null) {
            return Result.error("404", "用户不存在");
        }

        // 2. 检查用户是否有未结清的欠费
        if (user.getTotalMoney() != 0 && user.getTotalMoney() < 0) {
            return Result.error("403", "用户存在欠费，无法删除");
        }

        // 3. 检查用户借阅状态
        if (user.getBorrowingStatus() != 0 && user.getBorrowingStatus() == 1) {
            return Result.error("403", "用户借阅状态异常，无法删除");
        }

        // 4. 检查用户是否有逾期未还的图书
        LambdaQueryWrapper<BookWithUser> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(BookWithUser::getId, id)
                .le(BookWithUser::getDeadtime, new Date()); // 查询应还日期小于当前日期的记录

        List<BookWithUser> overdueRecords = bookWithUserMapper.selectList(queryWrapper);
        if (overdueRecords != null && !overdueRecords.isEmpty()) {
            return Result.error("403", "用户有逾期未还图书，无法删除");
        }

        // 5. 执行删除操作
        userMapper.deleteById(id);
        return Result.success();
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<User> wrappers = Wrappers.<User>lambdaQuery();
        if (StringUtils.isNotBlank(search)) {
            wrappers.like(User::getNickName, search);
        }
        wrappers.like(User::getRole, 2);
        Page<User> userPage = userMapper.selectPage(new Page<>(pageNum, pageSize), wrappers);
        return Result.success(userPage);
    }

    @GetMapping("/usersearch")
    public Result<?> findPage2(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               @RequestParam(defaultValue = "") String search1,
                               @RequestParam(defaultValue = "") String search2,
                               @RequestParam(defaultValue = "") String search3,
                               @RequestParam(defaultValue = "") String search4) {
        LambdaQueryWrapper<User> wrappers = Wrappers.<User>lambdaQuery();
        if (StringUtils.isNotBlank(search1)) {
            wrappers.like(User::getId, search1);
        }
        if (StringUtils.isNotBlank(search2)) {
            wrappers.like(User::getNickName, search2);
        }
        if (StringUtils.isNotBlank(search3)) {
            wrappers.like(User::getPhone, search3);
        }
        if (StringUtils.isNotBlank(search4)) {
            wrappers.like(User::getAddress, search4);
        }
        wrappers.like(User::getRole, 2);
        Page<User> userPage = userMapper.selectPage(new Page<>(pageNum, pageSize), wrappers);
        return Result.success(userPage);
    }

    //cy返回用户总金额和更新用户状态
    @GetMapping("/totalMoney/{userId}")
    public Result<?> getUserBalance(@PathVariable int userId) {
        // 参数校验
        if (userId == 0 || userId <= 0) {
            return Result.error("400", "无效的用户ID");
        }

        // 查询用户基本信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("404", "用户不存在");
        }

        // 计算逾期费用（以分为单位）
        int overdueFees = calculateOverdueFees(userId);

        // 将逾期费用转换为元，作为新的总金额（覆盖原有金额）
        double newTotalMoney = overdueFees / 100.0;

        // 更新数据库中的总金额和借阅状态
        updateUserBalanceAndStatus(userId, newTotalMoney);

        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("totalMoney", formatAmount(newTotalMoney * 100));
        result.put("borrowingStatus", newTotalMoney > 0 ? 1 : 0);

        return Result.success(result);
    }

    /**
     * 更新用户总金额和借阅状态
     */
    private void updateUserBalanceAndStatus(int userId, double newBalance) {
        User user = new User();
        user.setId(userId);
        user.setTotalMoney(newBalance);

        // 根据总金额设置借阅状态：大于0时不可借阅(1)，否则可借阅(0)
        user.setBorrowingStatus(newBalance > 0 ? 1 : 0);

        int rowsAffected = userMapper.updateById(user);
        if (rowsAffected == 0) {
            log.warn("更新用户余额和借阅状态失败，用户ID: {}", userId);
        }
    }

    /**
     * 格式化金额（分转元，保留两位小数）
     */
    private double formatAmount(double amountInCent) {
        return Math.round(amountInCent) / 100.0;
    }

    /**
     * 计算用户逾期费用（单位：分）
     */
    private int calculateOverdueFees(int userId) {
        // 查询用户所有逾期记录
        LambdaQueryWrapper<BookWithUser> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(BookWithUser::getId, userId)
                .lt(BookWithUser::getDeadtime, new Date());

        List<BookWithUser> overdueRecords = bookWithUserMapper.selectList(queryWrapper);

        // 计算总逾期费用
        int totalFees = 0;
        LocalDateTime currentDateTime = LocalDateTime.now();

        for (BookWithUser record : overdueRecords) {
            Date deadTime = record.getDeadtime();
            if (deadTime != null) {
                LocalDateTime deadLocalDateTime = deadTime.toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime();

                long daysBetween = calculateOverdueDays(deadLocalDateTime, currentDateTime);
                totalFees += daysBetween * 10; // 0.1元/天
            }
        }

        return totalFees;
    }

    /**
     * 计算逾期天数（不足一天按一天算）
     */
    private long calculateOverdueDays(LocalDateTime deadTime, LocalDateTime currentTime) {
        if (deadTime.isAfter(currentTime)) {
            return 0;
        }

        long days = ChronoUnit.DAYS.between(deadTime.toLocalDate(), currentTime.toLocalDate());
        if (deadTime.toLocalTime().isAfter(currentTime.toLocalTime()) || days == 0) {
            days++;
        }

        return Math.max(1, days);
    }

    //支付
    @GetMapping("/pay/{userId}")
    public Result<?> pay(@PathVariable int userId) {
        // 参数校验
        if (userId == 0 || userId <= 0) {
            return Result.error("400", "无效的用户ID");
        }

        // 查询用户当前状态
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("404", "用户不存在");
        }

        // 获取用户当前总金额
        double currentBalance = user.getTotalMoney() == 0 ? 0 : user.getTotalMoney();

        // 更新用户状态（总金额设为0，借阅状态设为0）
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setTotalMoney(0.0);
        updateUser.setBorrowingStatus(0);
        int rowsAffected = userMapper.updateById(updateUser);

        if (rowsAffected > 0) {
            // 返回操作结果
            Map<String, Object> result = new HashMap<>();
            result.put("userId", userId);
            result.put("originalBalance", currentBalance);
            result.put("newBalance", 0.0);
            result.put("status", "已结清");
            result.put("updateTime", LocalDateTime.now());

            return Result.success(result);
        } else {
            return Result.error("500", "更新用户状态失败，请稍后重试");
        }
    }

    //    根据id查找用户信息和用户借书记录（未还书籍）
    @GetMapping("/{id}/borrowings")
    public Result<?> getUserWithBorrowings(@PathVariable Integer id) {
        // 校验用户ID
        if (id == null || id <= 0) {
            return Result.error("400", "无效的用户ID");
        }

        // 查询用户信息
        User user = userMapper.selectById(id);
        if (user == null) {
            return Result.error("404", "用户不存在");
        }

        // 查询借书记录
        LambdaQueryWrapper<BookWithUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BookWithUser::getId, id)
                .orderByDesc(BookWithUser::getLendtime);

        List<BookWithUser> borrowings = bookWithUserMapper.selectList(queryWrapper);
        // 借阅未还数量
        int bookNumber = borrowings.size();
        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("userInfo", user);
        result.put("borrowings", borrowings);
        result.put("bookNumber", bookNumber);
        return Result.success(result);
    }
    // 预约
    // 要在还书上添加预约逻辑！！
    @PostMapping("/booking")
    public Result booking(@RequestParam Integer readerId,
                          @RequestParam String bookName){
        Reservation reservation = new Reservation();
        // 读者状态异常不可预约
        User reader = userMapper.selectById(readerId);
        if (reader.getTotalMoney() > 0 || reader.getBorrowingStatus() == 1) {
            return Result.error("405", "存在逾期未还书籍/未缴清欠款");
        }
        // 书已被预约
        if (reservationMapper.selectById(bookName) != null) {
            return Result.error("405", "此书已被预约");
        }
        //不能预约已经有借书的
        if (bookWithUserMapper.selectList(
                Wrappers.<BookWithUser>lambdaQuery()
                .eq(BookWithUser::getBookName, bookName)
                        .eq(BookWithUser::getId, readerId)) != null){
            return Result.error("405", "此用户已借阅此书,不可重复预约");
        }
        //限制预约（每个用户只能预约一本书）
        if (reservationMapper.selectOne(
                Wrappers.<Reservation>lambdaQuery()
                        .eq(Reservation::getReaderId, readerId)
        ) != null) {
            return Result.error("405","每个用户只能预约一本书");
        }
        // 书籍为可借阅状态时
//        Book book = bookMapper.selectOne(
//                Wrappers.<Book>lambdaQuery()
//                        .eq(Book::getIsbn, isbn)
//        );
//        if (Objects.equals(book.getStatus(), "1")){
//            reservation.setReaderId(readerId);
//            reservation.setIsbn(isbn);
//            Date stateTime = new Date();
//            LocalDate stateLocalDate = stateTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//            LocalDate endLocalDate = stateLocalDate.plusDays(5);
//            Date endTime = Date.from(endLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
//            reservation.setStateTime(stateTime);
//            reservation.setEndTime(endTime);
//            book.setStatus("2");
//        }
        // 书籍为被借阅状态时
//        if (Objects.equals(book.getStatus(), "0")) {
            reservation.setReaderId(readerId);
        reservation.setBookName(bookName);

            reservation.setIsbn(null);
            reservation.setStateTime(null);
            reservation.setEndTime(null);
//        }
        // 添加预约
        reservationMapper.insert(reservation);
        // 更新书籍状态
//        bookMapper.updateById(book);
        // 测试返回
//        Map<String, Object> result = new HashMap<>();
//        result.put("reservation", reservation);
        return Result.success();
    }

    // 取消预约
    // 在每次登录、访问借书页面（开始借书）、访问查询页面时进行刷新预约表
    @PostMapping("/cancelBooking")
    public Result cancelBooking() {
        Date currentTime = new Date();
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.lt("end_time", currentTime);
        List<Reservation> expiredReservations = reservationMapper.selectList(queryWrapper);
        // 更新每本书的状态
        if (expiredReservations != null && !expiredReservations.isEmpty()) {
           reservationMapper.delete(queryWrapper);
           Book book;
            for (Reservation expiredReservation : expiredReservations) {
                book = bookMapper.selectOne(
                        Wrappers.<Book>lambdaQuery()
                                .eq(Book::getIsbn, expiredReservation.getIsbn())
                );
                if (!Objects.equals(book.getStatus(), "2")){
                    break;
                }
                book.setStatus("1");
                bookMapper.updateById(book);
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("expiredReservations", expiredReservations);
        return Result.success(result);
    }

    // 借书
    @PostMapping("/borrowBook")
    public Result borrowBooks(@RequestParam Integer readerId,
                              @RequestParam String isbn
    ) {
        // 参数校验
        if (readerId <= 0 || StringUtils.isBlank(isbn)) {
            return Result.error("400", "参数错误");
        }
        // 用户
        User user = userMapper.selectById(readerId);
        // 检验用户是否可借书
        if (user.getBorrowingStatus() == 1)
            return Result.error("405", "当前用户不可借书，请先归还逾期书籍和缴清逾期费用");
        // 查找书籍是否存在
        Book book = bookMapper.selectOne(
                Wrappers.<Book>lambdaQuery()
                        .eq(Book::getIsbn, isbn)
        );
        // 判断借阅量是否满
        // 查询借书记录
        LambdaQueryWrapper<BookWithUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BookWithUser::getId, user.getId())
                .orderByDesc(BookWithUser::getLendtime);

        List<BookWithUser> borrowings = bookWithUserMapper.selectList(queryWrapper);
        // 借阅未还数量
        int bookNumber = borrowings.size();
        // 学生用户
        if (user.getRole() == 2) {
            if (bookNumber >= 10) {
                return Result.error("405", "当前用户借满");
            }
        } else
        // 教师用户
        if (user.getRole() == 3) {
            if (bookNumber >= 15) {
                return Result.error("405", "当前用户借满");
            }
        }
        if (book == null)
            return Result.error("405", "图书编号输入有误/该书未上架");
        // 检查书是否可借（状态是否为1/2）
        if (Objects.equals(book.getStatus(), "0")) {
            return Result.error("405", "当前书籍属于在借状态，请先归还");
        } else if (Objects.equals(book.getStatus(), "2")) {
            // 如果状态为2，检查预约表是否有预约信息
            // 预约人是否为借书人
            if (!readerId.equals(reservationMapper.selectOne(
                    Wrappers.<Reservation>lambdaQuery()
                            .eq(Reservation::getIsbn, isbn)).getReaderId())) {
                return Result.error("405", "该图书已被预约");
            } else
                // 删除预约记录
                reservationMapper.delete(
                        Wrappers.<Reservation>lambdaQuery()
                                .eq(Reservation::getIsbn, isbn));
        }
        // 更新书状态和借阅次数
        book.setStatus("0");
        // 更新书籍信息
        bookMapper.updateById(book);
//        book.setBorrownum(book.getBorrownum() + 1);
        // 更新借阅次数
        bookMapper.update(null,
                Wrappers.<Book>lambdaUpdate()
                        .eq(Book::getName, book.getName())
                        .set(Book::getBorrownum, book.getBorrownum() + 1)
        );

        // 新增借阅记录
        BookWithUser newBookWithUser = new BookWithUser();
        newBookWithUser.setId(readerId);
        newBookWithUser.setIsbn(isbn);
        newBookWithUser.setBookName(book.getName());
        newBookWithUser.setNickName(user.getNickName());
        // 借书时间
        Date lendtime = new Date();
        LocalDate lendLocalDate = lendtime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate deadLocalDate;
        // 计算应还时间（学生+60天教师+90）
        if (user.getRole() == 2)
            deadLocalDate = lendLocalDate.plusDays(60);
        else if (user.getRole() == 3)
            deadLocalDate = lendLocalDate.plusDays(90);
        else
            return Result.error("405", "非本校教职工/学生不允许在本馆借书");
        // 转换回Date
        Date deadtime = Date.from(deadLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        newBookWithUser.setLendtime(lendtime);
        newBookWithUser.setDeadtime(deadtime);
        newBookWithUser.setProlong(1);
        bookWithUserMapper.insert(newBookWithUser);
        // 新增借阅日志
        LendRecord newLR = new LendRecord();
        newLR.setReaderId(readerId);
        newLR.setIsbn(isbn);
        newLR.setBookname(book.getName());
        newLR.setLendTime(lendtime);
        newLR.setStatus("0");
        newLR.setBorrownum(book.getBorrownum() + 1);
        lendRecordMapper.insert(newLR);
        // 测试新增结果
//        Map<String, Object> result = new HashMap<>();
//        result.put("bookInfo", book);
//        result.put("newBookWithUser",newBookWithUser);
//        result.put("newLR", newLR);
        return Result.success();
    }

    // 还书
    @PostMapping("/returnBook")
    public Result returnBook(@RequestParam String isbn) {
        // 校验isbn
        if (StringUtils.isBlank(isbn)) {
            return Result.error("400", "参数错误");
        }

        // 根据isbn查找记录和用户信息
        BookWithUser recode = bookWithUserMapper.selectOne(
                Wrappers.<BookWithUser>lambdaQuery()
                        .eq(BookWithUser::getIsbn, isbn)
        );
        if (recode == null)
            return Result.error("404", "暂无借阅信息");
        Integer readerId = recode.getId();
        // 还当前编号书
        // 计算费用
        double fee = calculateFee(recode.getDeadtime());
        // 查找用户信息
        User readerUser = userMapper.selectById(readerId);
        // 更新用户信息
        double newBalance = readerUser.getTotalMoney() + fee;
        readerUser.setTotalMoney(newBalance);
        readerUser.setBorrowingStatus(newBalance > 0 ? 1 : 0);
        userMapper.updateById(readerUser);
        // 更新书籍状态
        Book book = bookMapper.selectOne(
                Wrappers.<Book>lambdaQuery()
                        .eq(Book::getIsbn, isbn)
        );
        book.setStatus("1");
        bookMapper.updateById(book);
        // 更新借阅日志信息
        // 直接更新符合条件的记录（更高效，避免先查询）
        Date returnTime = new Date();
        int updated = lendRecordMapper.update(
                null,
                Wrappers.<LendRecord>lambdaUpdate()
                        .set(LendRecord::getReturnTime, returnTime)
                        .set(LendRecord::getStatus, 1)
                        .eq(LendRecord::getReaderId, readerId)
                        .eq(LendRecord::getIsbn, isbn)
                        .eq(LendRecord::getStatus, 0)
        );
        if(updated == 0) {
            // 处理未找到记录的情况
            throw new RuntimeException("未找到待归还的借阅记录");
        }
        // 删除借阅记录
        int deleteCount = bookWithUserMapper.delete(
                Wrappers.<BookWithUser>lambdaQuery()
                        .eq(BookWithUser::getId, readerId)
                        .eq(BookWithUser::getIsbn, isbn)
        );
        // 检查是否成功删除借阅记录
        if (deleteCount == 0) {
            log.warn("删除借阅记录失败,用户ID: {}, ISBN: {}", readerId, isbn);
        }
        // 查看此书是否被预约
        Reservation reservation = reservationMapper.selectById(book.getName());
        // 已被预约并且没有预约开始时间
        if (reservation != null && reservation.getStateTime() == null){
            reservation.setStateTime(returnTime);
            // 预约书籍
            reservation.setIsbn(book.getIsbn());
            reservation.setEndTime(Date.from(returnTime.toInstant().atZone(ZoneId.systemDefault())
                    .toLocalDate().plusDays(5).atStartOfDay(ZoneId.systemDefault()).toInstant()));
            // 更新预约记录
            reservationMapper.updateById(reservation);
            // 更新书籍状态
            book.setStatus("2");
            bookMapper.updateById(book);
            // 使用 WebSocket 发送归还通知
            String message = "您的预约图书【" + book.getName() + "】已归还，可以前来借阅！";
            webSocketService.sendToUser(reservation.getReaderId(), message); // 发送通知
        }
        // 获取借书记录
        LambdaQueryWrapper<BookWithUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BookWithUser::getId, readerId)
                .orderByDesc(BookWithUser::getLendtime);
        List<BookWithUser> borrowings = bookWithUserMapper.selectList(queryWrapper);
        // 返回用户信息和还书提示
        Map<String, Object> result = new HashMap<>();
        result.put("fee", fee);
        result.put("newBalance", newBalance);
        result.put("userInfo", readerUser);
        result.put("borrowings", borrowings);
        return Result.success(result);
    }
    // 发送预约通知



    // 还书，根据用户id和书籍的isbn进行还书，并计算是否欠费，一本书超过一天0.1元
//    @PostMapping("/returnBook")
//    public Result<?> returnBook(@RequestParam Integer userId, @RequestParam String isbn) {
//        // 参数校验：检查用户ID是否有效和ISBN是否为空
//        if (userId <= 0 || StringUtils.isBlank(isbn)) {
//            return Result.error("400", "参数错误");
//        }
//
//        // 查询借阅记录：根据用户ID和ISBN查找借阅记录
//        BookWithUser record = bookWithUserMapper.selectOne(
//                Wrappers.<BookWithUser>lambdaQuery()
//                        .eq(BookWithUser::getId, userId)       // 匹配用户ID
//                        .eq(BookWithUser::getIsbn, isbn)       // 匹配图书ISBN
//        );
//
//        if (record == null) return Result.error("404", "借阅记录不存在");
//
//        // 计算逾期费用：调用计算方法计算应缴费用
//        double fee = calculateFee(record.getDeadtime());
//
//        // 更新用户信息
//        User user = userMapper.selectById(userId);
//        double newBalance = user.getTotalMoney() + fee;
//        user.setTotalMoney(newBalance);
//        user.setBorrowingStatus(newBalance > 0 ? 1 : 0);
//        userMapper.updateById(user);
//
//        // 删除借阅记录：根据用户ID和ISBN删除记录
//        int deleteCount = bookWithUserMapper.delete(
//                Wrappers.<BookWithUser>lambdaQuery()
//                        .eq(BookWithUser::getId, userId)       // 匹配用户ID
//                        .eq(BookWithUser::getIsbn, isbn)       // 匹配图书ISBN
//        );
//
//        // 检查是否成功删除记录
//        if (deleteCount == 0) {
//            log.warn("删除借阅记录失败，用户ID: {}, ISBN: {}", userId, isbn);
//        }
//
//        // 返回操作结果
//        Map<String, Object> result = new HashMap<>();
//        result.put("fee", fee);
//        result.put("newBalance", newBalance);
//        return Result.success(result);
//    }

    // 计算逾期费用的方法
    private double calculateFee(Date deadline) {
        // 如果没有应还日期，返回0费用
        if (deadline == null) return 0;

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 将Date类型的deadline转换为LocalDateTime类型
        LocalDateTime dueDate = deadline.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();

        // 如果当前时间在应还日期之前，没有逾期费用
        if (now.isBefore(dueDate)) return 0;

        // 计算逾期天数（按自然日计算）
        long days = ChronoUnit.DAYS.between(
                dueDate.toLocalDate(),  // 应还日期
                now.toLocalDate()        // 当前日期
        );

        // 计算费用：至少按1天计算，每天0.1元
        return Math.max(1, days) * 0.1;
    }
}


